package com.bootdo.system.config;

import com.bootdo.system.domain.*;
import com.bootdo.system.service.*;
import com.bootdo.system.utils.CalUtil;
import com.bootdo.system.utils.MyConstant;
import com.huobi.HuobiInfoUtils;
import com.huobi.constant.enums.DepositWithdrawTypeEnum;
import com.huobi.exception.SDKException;
import com.huobi.model.account.AccountLedger;
import com.huobi.model.market.MarketTicker;
import com.huobi.model.trade.Order;
import com.huobi.model.wallet.DepositWithdraw;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Component
public class ScheduledTask {
    @Autowired
    private BizhongService bizhongService;
    @Autowired
    private JiaoyijiluService jiaoyijiluService;
    @Autowired
    private JiaoyicelueService jiaoyicelueService;
    @Autowired
    private FrontuserService frontuserService;
    @Autowired
    private FrontlogService frontlogService;
    @Autowired
    private ZichanhistoryService zichanhistoryService;
    @Autowired
    private TibitableService tibitableService;

    //自动买卖
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 3000)
    public void autoSellandBuy() {

        //0.得到所有启动的策略
        List<JiaoyicelueDO> jiaoyicelueDOS = jiaoyicelueService.getList();
        log.info("自动买入卖出任务   ----开始---" + "策略jiaoyicelueDOS=" + jiaoyicelueDOS.size() +"  时间："+ LocalDateTime.now());
        //0.1 写一个方法，判断用户有效
        for (JiaoyicelueDO celue : jiaoyicelueDOS) {

            if (!frontuserService.judgeUser(celue.getUserid())) {
                //用户资产的钱不够或者有效时间不够
                continue;
            }

            BizhongDO bizhongDO = bizhongService.get(celue.getBizhongid());
            MarketTicker bizhongPrice = HuobiInfoUtils
                    .getBizhongPrice(bizhongDO.getBizhongname());
            //1.计算比例
            BigDecimal yinglibili = CalUtil.calPercent(bizhongPrice.getClose(), celue.getChicangjunjia());
            BigDecimal bucangdiefu = CalUtil.calPercentAbs(bizhongPrice.getClose(), celue.getChicangjunjia());
            //2.计算回调
            BigDecimal yinglihuidiao = CalUtil.calPercentAbs(bizhongPrice.getClose(), celue.getBuyhigh());
            BigDecimal bucanghuidiao = CalUtil.calPercent(bizhongPrice.getClose(), celue.getBuylow());

            System.out.println("盈利比例=" + yinglibili + "/" + celue.getZhiyingbili()
                    + "盈利回调=" + yinglihuidiao + "/" + celue.getZhiyinghuidiao()
                    + " 补仓跌幅=" + bucangdiefu + "/" + celue.getBucangdiefu()
                    + "补仓回调=" + bucanghuidiao + "/" + celue.getBucanghuidiao()
                    + LocalDateTime.now());

            //用户
            FrontuserDO user = frontuserService.get(celue.getUserid());
            System.out.println(user.getUserid() + "." + user.getUsername() + ":准备买入卖出");
            //3.两者+达到过价格的顶点  满足，创建卖出订单
            if (yinglibili.compareTo(celue.getZhiyingbili()) > 0 && yinglihuidiao.compareTo(celue.getZhiyinghuidiao()) > 0 &&
                    celue.getChicangshuliang().compareTo(BigDecimal.ZERO) > 0 &&
                    celue.getChicangjine().compareTo(BigDecimal.ZERO) > 0) {

                String clientOrderId = UUID.randomUUID().toString().replace("-", "");
                try {
                     Long sellOrder = HuobiInfoUtils.createLimitSellOrder(user.getHuobiapikey(), user.getHuobiapisecret(), clientOrderId,
                            bizhongDO.getBizhongname(), celue.getChicangshuliang());
                    if (sellOrder == null) {
                        continue;
                    }
                    System.out.println("******卖出okokok" + bizhongDO.getBizhongname() + "货币 orderId= = " + sellOrder);
                    //4.记录前台日志
                    frontlogService.saveSellLog(user.getUserid(), 2, bizhongDO.getBizhongname(),
                            "" + sellOrder, celue.getChicangshuliang(), bizhongPrice.getClose(), clientOrderId);
                    //5.交易记录保存
                    jiaoyijiluService.savejilu(user.getUserid(), "" + sellOrder, celue.getChicangshuliang(), bizhongPrice.getClose(),
                            celue.getNowbuchangcishu(), bizhongDO, 1, clientOrderId);

                    celue.setBucangcishu(0);
                    celue.setNowbuchangcishu(0);

                    celue.setCeluestatus(0);
                    jiaoyicelueService.update(celue);
                } catch (SDKException e) {
                    System.out.println("卖出异常=" + e);
                }

            }
            //买入任务 条件= 跌幅比例  毁掉  启动   补仓次数小于上限
            if ((bucangdiefu.compareTo(celue.getBucangdiefu()) > 0 && bucanghuidiao.compareTo(celue.getBucanghuidiao()) > 0
                    && celue.getBucangcishu() <= celue.getBeitoushangxian())
                    ||
                    //首次买入策略
                    (celue.getCeluestatus() == 1 && celue.getBucangcishu() == 0)
                    ) {

                String clientOrderId = UUID.randomUUID().toString().replace("-", "");

                double pow = Math.pow(2, celue.getBucangcishu() == null ? 0 : celue.getBucangcishu());

                BigDecimal price = celue.getFirstamount().multiply(new BigDecimal(pow)).setScale(2, BigDecimal.ROUND_HALF_UP);

                BigDecimal amount = price.divide(bizhongPrice.getClose(), 10, BigDecimal.ROUND_HALF_UP);


                BigDecimal nowprice = bizhongPrice.getClose();
                try {
                    System.out.println(user.getUsername() + "开始----买入额度=" + price + "  买入数量=" + amount + "买入" + bizhongDO.getBizhongname());

                    long buyOrder = HuobiInfoUtils.createBuyOrder(user.getHuobiapikey(), user.getHuobiapisecret(), clientOrderId,
                            bizhongDO.getBizhongname(), nowprice, price);
                    System.out.println(user.getUsername() + "  买入额度=" + price + "  买入数量=" + amount + "买入" + bizhongDO.getBizhongname() + "货币 buyOrder = " + buyOrder);
                    //3.1如果是单次策略，运行完设置状态停止
                    celue.setNowbuchangcishu(celue.getNowbuchangcishu() + 1);
                    celue.setBucangcishu(celue.getBucangcishu() + 1);
                    celue.setBuyhigh(nowprice);
                    celue.setBuylow(nowprice);
                    jiaoyicelueService.update(celue);
                    //4.记录前台日志
                    frontlogService.saveSellLog(user.getUserid(), 1, bizhongDO.getBizhongname(),
                            buyOrder + "", amount, nowprice, clientOrderId);
                    //5.交易记录保存
                    jiaoyijiluService.savejilu(user.getUserid(), "" + buyOrder, amount, bizhongPrice.getClose(),
                            celue.getBucangcishu(), bizhongDO, 0, clientOrderId);

                } catch (SDKException e) {
                    System.out.println("购买异常=" + e);

                } catch (NullPointerException e) {
                    System.out.println("购买空指针异常=" + e);
                    //前台日志
                    celue.setCeluestatus(0);
                    jiaoyicelueService.update(celue);
                }
            }
        }
        //5.定时任务检测是否成功，成功减少持仓比例，修改对应的持仓均价。
        log.info("自动买入卖出任务   ----    完毕");
    }

    //得到实时价格
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 3000)
    public void scheduledTask() {
        log.info("定时任务 得到实时价格  任务执行时间：" + LocalDateTime.now());
        List<BizhongDO> bizhongDOS = bizhongService.list(new HashMap<>());
        List<MarketTicker> bizhongPrice = HuobiInfoUtils.getBizhongPrice();
        for (MarketTicker m : bizhongPrice) {
            for (BizhongDO bi : bizhongDOS) {
                if (m.getSymbol().equals(bi.getBizhongname())) {
                    bi.setNowprice(m.getClose());
                    bi.setZhangfu(m.getHigh().subtract(m.getLow()));
                    bizhongService.update(bi);
                }
            }
        }
    }


    //充钱检测
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 20000)
    public void scheduledTaskCaluserchongzhi() {
        log.info("计算所有用户冲币  任务执行时间：" + LocalDateTime.now());

        FrontuserDO admin = frontuserService.get(1L);

        if (StringUtils.isBlank(admin.getHuobiapikey()) || StringUtils.isBlank(admin.getHuobiapisecret())) {
            System.out.println("admin没有设置火币api，无法检查充值记录");
            return;
        }

        try {
            List<DepositWithdraw> walletLiushui = HuobiInfoUtils
                    .getWalletLiushui(admin.getHuobiapikey(), admin.getHuobiapisecret(), DepositWithdrawTypeEnum.DEPOSIT);

            List<FrontuserDO> users = frontuserService.userListOrderId();

            for (DepositWithdraw liushui : walletLiushui) {
                ZichanhistoryDO zichanhistoryDO = zichanhistoryService.getByBeizhu(liushui.getTxHash());
                if (zichanhistoryDO != null) {
                    continue;
                }
                if (zichanhistoryDO == null) {
                    for (FrontuserDO user : users) {
                        if (StringUtils.isNotBlank(user.getHuobiapikey()) && StringUtils.isNotBlank(user.getHuobiapisecret())) {
                            try {
                                List<DepositWithdraw> userwalletLiushui = HuobiInfoUtils
                                        .getWalletLiushui(user.getHuobiapikey(), user.getHuobiapisecret(), DepositWithdrawTypeEnum.WITHDRAW);

                                for (DepositWithdraw userliushui : userwalletLiushui) {
                                    if (String.valueOf(userliushui.getId()).equals(liushui.getTxHash())) {
                                        System.out.println(new Date() + " " + user.getUsername() + "充值：" + liushui.getAmount());
                                        updateUserZichan(user, liushui);
                                        break;
                                    }
                                }
                                Thread.sleep(300);

                            } catch (Exception e) {
                                System.out.println("充钱检测异常=" + e);
                            }

                        }

                    }
                }
            }

        } catch (SDKException e) {
            System.out.println("得到充币提币账单SDKexception=" + e);
        }

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.REPEATABLE_READ)
    public void updateUserZichan(FrontuserDO user, DepositWithdraw liushui) {
        ZichanhistoryDO byBeizhu = zichanhistoryService.getByBeizhu(liushui.getTxHash());
        if (byBeizhu==null) {
            user.setZichan(user.getZichan().add(liushui.getAmount()));
            frontuserService.update(user);
            //保存资产记录  日志记录
            FrontlogDO log = new FrontlogDO();
            log.setUserid(1L);
            log.setCreatetime(new Date());
            log.setChengjiaojia(liushui.getAmount());
            log.setContent("用户:" + user.getUsername() + " 充值了" + liushui.getAmount() +
                    "  地址：" + liushui.getAddress());
            log.setBizhongname(liushui.getCurrency());
            log.setJiaoyitype("0");
            log.setBeizhu("区块链交易ID=" + liushui.getTxHash());
            frontlogService.save(log);
            //前端日志
            log.setUserid(user.getUserid());
            frontlogService.save(log);
            //资产历史
            ZichanhistoryDO zichanhistoryDO = new ZichanhistoryDO();
            zichanhistoryDO.setCreatetime(new Date());
            zichanhistoryDO.setUserid(user.getUserid());
            zichanhistoryDO.setJiaoyitype("充值");
            zichanhistoryDO.setAmount(liushui.getAmount());
            zichanhistoryDO.setBeizhu(liushui.getTxHash());
            zichanhistoryService.save(zichanhistoryDO);
        }

    }

    //更新用户账户id
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 8000)
    public void scheduledTasktransactId() {
        List<FrontuserDO> list = frontuserService.list(new HashMap<>());
        list.forEach(user -> {
            if (StringUtils.isNotBlank(user.getHuobiapikey()) && StringUtils.isNotBlank(user.getHuobiapisecret())) {
                try {
                    //System.out.println("更新用户账户  "+user.getUsername());
                    long accountId = HuobiInfoUtils.account_id(user.getHuobiapikey(), user.getHuobiapisecret());
                    user.setTransactId(accountId);
                    user.setLoginpass(null);
                    user.setPaypass(null);
                    if (user.getTransactId() != accountId) {
                        frontuserService.update(user);
                        log.info("更新用户账户id=" + user.getTransactId());
                    }
                } catch (SDKException e) {
                    System.out.println("更新用户账户id异常=" + e);
                    e.printStackTrace();
                }

            }
        });
    }

    //涨幅自动更新且修改了策略的最高最低价钱
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 4000)
    public void calzhangfu() {
        //System.out.println("6s涨幅自动更新");
        List<JiaoyicelueDO> list = jiaoyicelueService.list(new HashMap<>());
        try{
            list.forEach(jiaoyicelueDO -> {
                //币种名字
                BizhongDO bizhongDO = bizhongService.get(jiaoyicelueDO.getBizhongid());
                if (jiaoyicelueDO.getChicangjunjia().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal subtract = bizhongDO.getNowprice().subtract(jiaoyicelueDO.getChicangjunjia());
                    BigDecimal divide = subtract.divide(jiaoyicelueDO.getChicangjunjia(), 4, BigDecimal.ROUND_HALF_UP);
                    jiaoyicelueDO.setZhangfu(divide);
                    if(jiaoyicelueDO.getBuyhigh()==null){
                        jiaoyicelueDO.setBuyhigh(BigDecimal.ZERO);
                    }
                    if(jiaoyicelueDO.getBuylow()==null){
                        jiaoyicelueDO.setBuylow(BigDecimal.ZERO);
                    }
                    if (bizhongDO.getNowprice().compareTo(jiaoyicelueDO.getBuyhigh()) > 0) {
                        System.out.println("***修改策略的买入最高价 " + bizhongDO.getBizhongname() + "  现在价格：" + bizhongDO.getNowprice());
                        jiaoyicelueDO.setBuyhigh(bizhongDO.getNowprice());
                    }
                    if (bizhongDO.getNowprice().compareTo(jiaoyicelueDO.getBuylow()) < 0) {
                        System.out.println("***修改策略的买入最低价 " + bizhongDO.getBizhongname() + "  现在价格：" + bizhongDO.getNowprice());
                        jiaoyicelueDO.setBuylow(bizhongDO.getNowprice());
                    }
                    jiaoyicelueService.updateZhangfu(jiaoyicelueDO);
                    //System.out.println("涨幅自动更新：" + divide);
                }
            });
        }catch (Exception e){
            log.error("涨幅自动更新抛出异常："+e);
            e.printStackTrace();

        }

    }


    //检测是否订单成功
    @Async("taskExecutor")
    @Scheduled(fixedDelay = 5000)
    public void getischengjiao() {
        //5.定时任务检测是否订单成功，成功减少持仓比例，修改对应的持仓均价。
        log.info("3s定时任务  查看是否成交");
        List<JiaoyijiluDO> jiaoyijiluDOS = jiaoyijiluService.list(new HashMap<>());
        for (JiaoyijiluDO jiaoyijilu : jiaoyijiluDOS) {

            FrontuserDO user = frontuserService.get(jiaoyijilu.getUserid());
            //火币订单
            if (user == null || !frontuserService.judgeUser(user.getUserid())) {
                //用户资产的钱不够或者有效时间不够
                continue;
            }
            if (jiaoyijilu.getBeizhu() == null || jiaoyijilu.getBeizhu().equals("")) {
                continue;
            }
            if(jiaoyijilu.getChengjiaojine()!=null&&jiaoyijilu.getChengjiaojine().compareTo(BigDecimal.ZERO)>=0){
                continue;
            }

            //System.out.println("查询火币订单=" + jiaoyijilu.getOrderno());
            try {
                Thread.sleep(100);
                Order order = HuobiInfoUtils.Order(user.getHuobiapikey(), user.getHuobiapisecret(), Long.parseLong(jiaoyijilu.getOrderno()));
                //
                //订单的状态是完全成交的
                if (order.getState().equals("filled")) {
                    //更具用户id和币种id得到策略
                    JiaoyicelueDO jiaoyicelueDO = jiaoyicelueService.getMairuPriceByUidAndBid(jiaoyijilu.getUserid(), jiaoyijilu.getBizhongid());
                    //判断这个订单是新的有效的
                    FrontlogDO log = frontlogService.getByBeizhu(jiaoyijilu.getOrderno() + "-success");
                    if (log == null) {
                        System.out.println("-----查询火币订单结果=" + order);
                        if (jiaoyijilu.getJiaoyitype().equals("0")) {
                            //买入成功
                            buyinto(jiaoyijilu, jiaoyicelueDO, order, user);
                        } else {
                            //卖出成功
                            sellout(jiaoyijilu, jiaoyicelueDO, order, user);
                        }
                    }
                }
            } catch (SDKException e) {
                System.out.println("----查询订单，火币sdk异常----" + e);
            }catch (Exception e){
                System.out.println("----查询订单，异常----" + e);
            }
        }
    }

    //订单卖出方法
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void sellout(JiaoyijiluDO jiaoyijilu, JiaoyicelueDO jiaoyicelueDO, Order order, FrontuserDO user) {

        System.out.println("*******卖出订单，Order=" + order);
        if (!order.getState().equals("filled")) {
            return;
        }
        BigDecimal yingli = order.getFilledCashAmount().subtract(jiaoyicelueDO.getChicangjine()).subtract(order.getFilledFees());
        jiaoyijilu.setYingli(yingli);

        if (jiaoyicelueDO.getChicangjine() == null) {
            jiaoyicelueDO.setChicangjine(BigDecimal.ZERO);
        }
        if (jiaoyicelueDO.getChicangshuliang() == null) {
            jiaoyicelueDO.setChicangshuliang(BigDecimal.ZERO);
        }
        //卖出之后才开始下一次的买入
        if (jiaoyicelueDO.getXunhuantype() == 1) {
            jiaoyicelueDO.setCeluestatus(1);
        }

        //设置持仓金额和数量
        jiaoyicelueDO.setChicangjine(order.getFilledCashAmount().subtract(jiaoyicelueDO.getChicangjine()));
        jiaoyicelueDO.setChicangshuliang(jiaoyicelueDO.getChicangshuliang().subtract(order.getFilledAmount()));
        if (jiaoyicelueDO.getChicangshuliang().compareTo(BigDecimal.ZERO) > 0) {
            jiaoyicelueDO.setChicangjunjia(jiaoyicelueDO.getChicangjine().
                    divide(jiaoyicelueDO.getChicangshuliang(), 6, BigDecimal.ROUND_UP));

        } else {
            jiaoyicelueDO.setChicangjunjia(BigDecimal.ZERO);
        }

        String logbeizhu = jiaoyijilu.getOrderno() + "-success";

        frontlogService.savelog(logbeizhu, order, jiaoyijilu.getUserid(), "1");

        jiaoyijilu.setChengjiaojine(order.getFilledCashAmount());//成交金额
        jiaoyijilu.setChengjiaoshuliang(order.getFilledAmount());
        jiaoyijilu.setChengjiaojunjia(order.getFilledCashAmount().divide(order.getFilledAmount(), 8, BigDecimal.ROUND_UP));
        jiaoyijilu.setShouxufei(order.getFilledFees());//手续费
        if(jiaoyijilu.getBeizhu().equals(MyConstant.USER_SELL_ORDER)){
            jiaoyijilu.setYingli(BigDecimal.ZERO);
        }
        //设置为全部初识化
        jiaoyicelueDO.setChicangjunjia(BigDecimal.ZERO);
        jiaoyicelueDO.setChicangshuliang(BigDecimal.ZERO);
        jiaoyicelueDO.setChicangjine(BigDecimal.ZERO);
        jiaoyicelueDO.setBucangcishu(0);
        jiaoyicelueDO.setNowbuchangcishu(0);
        jiaoyicelueDO.setZhangfu(BigDecimal.ZERO);
        //更新信息
        jiaoyicelueService.update(jiaoyicelueDO);
        jiaoyijiluService.update(jiaoyijilu);

    }


    //买入方法
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void buyinto(JiaoyijiluDO jiaoyijilu, JiaoyicelueDO jiaoyicelueDO, Order order, FrontuserDO user) {
        if (!order.getState().equals("filled")) {
            return;
        }
        System.out.println("订单" + jiaoyijilu.getBeizhu() + "全部成交" + " 更新持仓=" + jiaoyicelueDO);
        jiaoyijilu.setYingli(BigDecimal.ZERO);
        //防止重复买入
        if (jiaoyicelueDO.getChicangjine() == null) {
            jiaoyicelueDO.setChicangjine(BigDecimal.ZERO);
        }
        if (jiaoyicelueDO.getChicangshuliang() == null) {
            jiaoyicelueDO.setChicangshuliang(BigDecimal.ZERO);
        }

        jiaoyicelueDO.setChicangjine(jiaoyicelueDO.getChicangjine().add(order.getFilledCashAmount()));
        jiaoyicelueDO.setChicangshuliang(jiaoyicelueDO.getChicangshuliang().add(order.getFilledAmount()));
        jiaoyicelueDO.setChicangjunjia(jiaoyicelueDO.getChicangjine().divide(jiaoyicelueDO.getChicangshuliang(), 6, BigDecimal.ROUND_UP));

        String logbeizhu = jiaoyijilu.getOrderno() + "-success";

        frontlogService.savelog(logbeizhu, order, jiaoyijilu.getUserid(), "0");

        jiaoyijilu.setChengjiaojine(order.getFilledCashAmount());//成交金额
        jiaoyijilu.setChengjiaoshuliang(order.getFilledAmount());
        jiaoyijilu.setChengjiaojunjia(order.getFilledCashAmount().divide(order.getFilledAmount(), 8, BigDecimal.ROUND_UP));
        jiaoyijilu.setShouxufei(order.getFilledFees());//手续费
        //更新信息
        jiaoyicelueService.update(jiaoyicelueDO);
        jiaoyijiluService.update(jiaoyijilu);
    }


    //每天0点分钱
    @Async("taskExecutor")
    @Scheduled(cron = "1 0 0 * * ?")
    public void everyday12fenqian() {
        log.info("每天凌晨0点0分1秒开始结算昨天的盈利");
        //每天0点扣除用户资产
        List<FrontuserDO> userList = frontuserService.list(null);
        userList.stream().filter(user ->{
            return user.getZichan() != null && user.getZichan().compareTo(BigDecimal.ZERO) > 0;
        }).forEach(user ->{
            //今日盈利的用户
            BigDecimal todayYingli = jiaoyijiluService.getYestdayYingli(user.getUserid());
            //盈利不为空  并且大于零
            if (todayYingli != null && todayYingli.compareTo(BigDecimal.ZERO) > 0) {
                //20%的盈利
                BigDecimal fenzhangallmoney = todayYingli.multiply(new BigDecimal("0.2"));
                //账户扣款
                log.info("今日盈利的用户：{}；盈利为：{}需要扣除20%为：{}",user.getNickname(),todayYingli,fenzhangallmoney);
                user.setZichan(user.getZichan().subtract(fenzhangallmoney));
                user.setPaypass(null);
                user.setLoginpass(null);
                frontuserService.update(user);
                ZichanhistoryDO zichanhistoryDO = new ZichanhistoryDO();
                zichanhistoryDO.setUserid(user.getUserid());
                zichanhistoryDO.setAmount(BigDecimal.ZERO.subtract(fenzhangallmoney));
                zichanhistoryDO.setCreatetime(new Date());
                zichanhistoryDO.setJiaoyitype("扣取信誉值");
                zichanhistoryDO.setBeizhu("利润扣减,来自：" + user.getUsername());
                zichanhistoryService.save(zichanhistoryDO);
                //机器人的盈利
                BigDecimal jiqirenmoney = fenzhangallmoney.multiply(new BigDecimal("0.5"));
                log.info("给admin加的盈利为:{}的50%为：{}",fenzhangallmoney,jiqirenmoney);
                FrontuserDO admin = frontuserService.get(1L);
                admin.setZichan(admin.getZichan().add(jiqirenmoney));
                admin.setLoginpass(null);
                admin.setPaypass(null);
                frontuserService.update(admin);
                ZichanhistoryDO adminzichanhistory = new ZichanhistoryDO();
                adminzichanhistory.setUserid(admin.getUserid());
                adminzichanhistory.setAmount(jiqirenmoney);
                adminzichanhistory.setCreatetime(new Date());
                adminzichanhistory.setJiaoyitype("信誉值奖");
                adminzichanhistory.setBeizhu("利润-机器人,来自：" + user.getUsername());
                zichanhistoryService.save(adminzichanhistory);
                //上级盈利 10
                BigDecimal shangjifenzhangallmoney = fenzhangallmoney.multiply(new BigDecimal("0.5"));
                //第一个上级
                FrontuserDO parent1 = frontuserService.get(user.getParentid());
                BigDecimal multiply = parent1.getDianshu().multiply(shangjifenzhangallmoney);
                parent1.setZichan(parent1.getZichan().add(multiply));
                parent1.setLoginpass(null);
                parent1.setPaypass(null);
                frontuserService.update(parent1);
                log.info("第一个上级{}的分红为：{}的10%；实际得到的为：{}",parent1.getNickname(),fenzhangallmoney,multiply);
                ZichanhistoryDO parent1zichanhistory = new ZichanhistoryDO();
                parent1zichanhistory.setUserid(parent1.getUserid());
                parent1zichanhistory.setAmount(jiqirenmoney);
                parent1zichanhistory.setCreatetime(new Date());
                parent1zichanhistory.setJiaoyitype("信誉值奖");
                parent1zichanhistory.setBeizhu("利润-作为第一上级,来自：" + user.getUsername());
                zichanhistoryService.save(parent1zichanhistory);
                shangjiUserfenzhang(parent1.getUserid(), parent1.getParentid(), shangjifenzhangallmoney);
            }
        });
    }

    //分钱递归方法
    /*
    a为初级代理，a推广b，b推广c！a点数100..a给b设置了80.b给c设置了50(只能设置80-0)，

    如果c下面收益100u，扣除20%收益！10u推广 则：c有5u，b有3u，a有2u，机器人10u
     */
    public void shangjiUserfenzhang(Long userid,long parentid, BigDecimal parentMoney) {

        FrontuserDO userDO = frontuserService.get(userid);
        //我的父节点
        FrontuserDO parent = frontuserService.get(parentid);
        //父节点的利润
        if (parent == null || parentid == 0L) {
            return;
        }
        BigDecimal tuiguanglirun = parent.getDianshu().subtract(userDO.getDianshu()).multiply(parentMoney).setScale(8, RoundingMode.HALF_UP);

        System.out.println("一级以上父节点:" + parent.getUsername() + "   利润:" + tuiguanglirun);
        //设置资产
        parent.setZichan(parent.getZichan().add(tuiguanglirun));
        //更新资产
        parent.setLoginpass(null);
        parent.setPaypass(null);
        frontuserService.update(parent);
        ZichanhistoryDO history = new ZichanhistoryDO();
        history.setUserid(parentid);
        history.setAmount(tuiguanglirun);
        history.setCreatetime(new Date());
        history.setJiaoyitype("信誉值奖");
        history.setBeizhu("利润-下级盈利");
        zichanhistoryService.save(history);
        //在上一级
        if (parent.getParentid() != null && parentid != 0) {
            shangjiUserfenzhang(parent.getUserid(),parent.getParentid(), parentMoney);
        } else {
            return;
        }

    }


    //检查用户的货币策略
    @Async("taskExecutor")
    @Scheduled(cron = "*/5 * * * * ?")
    public void configureTasksBizhong() {
        //log.info("5s定时：检查用户的货币策略是否完整");
        List<FrontuserDO> frontuserDOS = frontuserService.list(new HashMap<>());
        List<BizhongDO> bizhongDOS = bizhongService.list(new HashMap<>());

        for (FrontuserDO u : frontuserDOS) {
            //log.info("检查用户"+u.getUsername()+"的货币策略"+u.getUserid());
            for (BizhongDO bizhong : bizhongDOS) {
                JiaoyicelueDO jiaoyicelueDO = jiaoyicelueService.getCelueByUserIdAndBizhongId(u.getUserid(), bizhong.getId());
                if (jiaoyicelueDO == null) {
                    jiaoyicelueService.saveCelue(u, bizhong);
                    log.info("用户" + u.getUsername() + " 新货币策略保存 货币：" + bizhong.getBizhongname());
                }
            }
        }
    }



}

